<template>
  <view class="date-picker-container">
    <view class="date-picker-input" @click="showDatePicker">
      <text class="date-label">{{ label }}</text>
      <view class="date-value">
        <text>{{ displayValue || placeholder }}</text>
        <text class="date-icon">&#xe65e;</text>
      </view>
    </view>
    
    <uni-popup ref="datePopup" type="bottom">
      <view class="picker-container">
        <view class="picker-header">
          <text class="cancel-btn" @click="cancelSelect">取消</text>
          <text class="title">选择日期</text>
          <text class="confirm-btn" @click="confirmSelect">确定</text>
        </view>
        <picker-view class="picker-view" :value="dateArray" @change="handleDateChange">
          <picker-view-column>
            <view class="picker-item" v-for="(year, index) in years" :key="'year-' + index">{{ year }}年</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(month, index) in months" :key="'month-' + index">{{ month }}月</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(day, index) in days" :key="'day-' + index">{{ day }}日</view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue';

export default defineComponent({
  name: 'DatePicker',
  props: {
    value: {
      type: String,
      default: ''
    },
    label: {
      type: String,
      default: '日期'
    },
    placeholder: {
      type: String,
      default: '请选择日期'
    }
  },
  emits: ['update:value', 'change'],
  setup(props, { emit }) {
    const datePopup = ref<any>(null);
    const selectedYear = ref(new Date().getFullYear());
    const selectedMonth = ref(new Date().getMonth() + 1);
    const selectedDay = ref(new Date().getDate());
    const tempYear = ref(selectedYear.value);
    const tempMonth = ref(selectedMonth.value);
    const tempDay = ref(selectedDay.value);
    
    // 生成年份数组（当前年份前后10年）
    const years = computed(() => {
      const currentYear = new Date().getFullYear();
      const yearArray = [];
      for (let i = currentYear - 10; i <= currentYear + 10; i++) {
        yearArray.push(i);
      }
      return yearArray;
    });
    
    // 生成月份数组
    const months = computed(() => {
      const monthArray = [];
      for (let i = 1; i <= 12; i++) {
        monthArray.push(i);
      }
      return monthArray;
    });
    
    // 生成天数数组（根据年月计算）
    const days = computed(() => {
      const dayArray = [];
      const daysInMonth = new Date(tempYear.value, tempMonth.value, 0).getDate();
      for (let i = 1; i <= daysInMonth; i++) {
        dayArray.push(i);
      }
      return dayArray;
    });
    
    // 当前选择的日期索引数组
    const dateArray = computed(() => {
      return [
        years.value.indexOf(tempYear.value),
        months.value.indexOf(tempMonth.value),
        days.value.indexOf(tempDay.value) > -1 ? days.value.indexOf(tempDay.value) : 0
      ];
    });
    
    // 格式化日期显示
    const displayValue = computed(() => {
      if (!props.value) return '';
      const year = props.value.substring(0, 4);
      const month = props.value.substring(4, 6);
      const day = props.value.substring(6, 8);
      return `${year}年${month}月${day}日`;
    });
    
    // 处理日期选择变化
    const handleDateChange = (e: any) => {
      const values = e.detail.value;
      tempYear.value = years.value[values[0]];
      tempMonth.value = months.value[values[1]];
      
      // 确保选择的日期有效
      const maxDay = new Date(tempYear.value, tempMonth.value, 0).getDate();
      tempDay.value = Math.min(days.value[values[2]] || 1, maxDay);
    };
    
    // 显示日期选择器
    const showDatePicker = () => {
      if (datePopup.value) {
        // 初始化临时值为当前选中值
        if (props.value) {
          const year = parseInt(props.value.substring(0, 4));
          const month = parseInt(props.value.substring(4, 6));
          const day = parseInt(props.value.substring(6, 8));
          
          tempYear.value = year;
          tempMonth.value = month;
          tempDay.value = day;
        } else {
          tempYear.value = selectedYear.value;
          tempMonth.value = selectedMonth.value;
          tempDay.value = selectedDay.value;
        }
        
        datePopup.value.open();
      }
    };
    
    // 取消选择
    const cancelSelect = () => {
      if (datePopup.value) {
        datePopup.value.close();
      }
    };
    
    // 确认选择
    const confirmSelect = () => {
      selectedYear.value = tempYear.value;
      selectedMonth.value = tempMonth.value;
      selectedDay.value = tempDay.value;
      
      // 格式化为YYYYMMDD格式
      const formattedMonth = tempMonth.value.toString().padStart(2, '0');
      const formattedDay = tempDay.value.toString().padStart(2, '0');
      const dateValue = `${tempYear.value}${formattedMonth}${formattedDay}`;
      
      emit('update:value', dateValue);
      emit('change', dateValue);
      
      if (datePopup.value) {
        datePopup.value.close();
      }
    };
    
    // 初始化时解析传入的值，但不自动打开选择器
    onMounted(() => {
      if (props.value) {
        const year = parseInt(props.value.substring(0, 4));
        const month = parseInt(props.value.substring(4, 6));
        const day = parseInt(props.value.substring(6, 8));
        
        selectedYear.value = year;
        selectedMonth.value = month;
        selectedDay.value = day;
      }
    });
    
    return {
      datePopup,
      years,
      months,
      days,
      dateArray,
      displayValue,
      handleDateChange,
      showDatePicker,
      cancelSelect,
      confirmSelect
    };
  }
});
</script>

<style lang="scss">
.date-picker-container {
  width: 100%;
  margin-bottom: 20rpx;
}

.date-picker-input {
  display: flex;
  flex-direction: column;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.date-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.date-value {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  color: #333;
}

.date-icon {
  font-family: "iconfont";
  color: #999;
}

.picker-container {
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.cancel-btn {
  color: #999;
  font-size: 28rpx;
}

.title {
  color: #333;
  font-size: 30rpx;
  font-weight: 500;
}

.confirm-btn {
  color: #8bc4a0;
  font-size: 28rpx;
}

.picker-view {
  width: 100%;
  height: 480rpx;
}

.picker-item {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  color: #333;
}
</style> 